
import pandas as pd
import numpy as np

def analyze_ahp_from_excel(excel_path, sheet_name="Sheet1"):
    # ====== Step 1: 读取打分矩阵 ======
    xls = pd.ExcelFile(excel_path)
    df = xls.parse(sheet_name)

    score_columns = [col for col in df.columns if '——' in col and '重要程度' in col]
    expert_scores = df[score_columns].iloc[0]

    level1_indicators = [
        "管材特性", "敷设位置", "压力等级", "管龄",
        "施工质量问题", "环境影响因素", "运行与维护情况"
    ]

    pairs = []
    values = []
    for col in score_columns:
        title = col.split("（")[0]
        parts = title.split("——")
        if len(parts) == 2:
            a, b = parts[0].strip(), parts[1].strip()
            if a in level1_indicators and b in level1_indicators:
                pairs.append((a, b))
                values.append(float(expert_scores[col]))

    n = len(level1_indicators)
    matrix = np.ones((n, n))
    for (a, b), val in zip(pairs, values):
        i = level1_indicators.index(a)
        j = level1_indicators.index(b)
        matrix[i, j] = val
        matrix[j, i] = 1 / val

    df_matrix = pd.DataFrame(matrix, index=level1_indicators, columns=level1_indicators)

    # ====== Step 2: 计算权重和一致性 ======
    A = df_matrix.values
    eigenvalues, eigenvectors = np.linalg.eig(A)
    max_index = np.argmax(np.real(eigenvalues))
    max_eigenvalue = np.real(eigenvalues[max_index])
    weight_vector = np.real(eigenvectors[:, max_index])
    weights = weight_vector / np.sum(weight_vector)

    CI = (max_eigenvalue - n) / (n - 1)
    RI_dict = {1: 0.00, 2: 0.00, 3: 0.58, 4: 0.90, 5: 1.12, 6: 1.24, 7: 1.32,
               8: 1.41, 9: 1.45, 10: 1.49}
    RI = RI_dict.get(n, 1.49)
    CR = CI / RI if RI != 0 else 0

    # ====== Step 3: 一致性判断 ======
    if CR < 0.1:
        result_dict = {ind: round(float(w), 4) for ind, w in zip(level1_indicators, weights)}
        # 保存结果为 JSON 文件（与输入 Excel 同目录）
        import os
        import json
        output_dir = os.path.dirname(os.path.abspath(excel_path))
        output_path = os.path.join(output_dir, "一级指标权重.json")
        with open(output_path, 'w', encoding='utf-8') as f:
            json.dump(result_dict, f, ensure_ascii=False, indent=2)
        return result_dict
    else:
        return f"一致性检验未通过 (CR={CR:.4f})"


# 使用示例（替换为你的 Excel 路径）
if __name__ == "__main__":
    excel_path = "/Users/lhd/Downloads/319504894_按文本_AHP（层次分析法）一级指标专家打分表_1_1.xlsx"  # 修改为本地路径
    result = analyze_ahp_from_excel(excel_path)
    print(result)
    import os, json
    if isinstance(result, dict):
        project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
        output_dir = os.path.join(project_root, "数据")
        os.makedirs(output_dir, exist_ok=True)
        output_path = os.path.join(output_dir, "一级指标权重.json")
        with open(output_path, 'w', encoding='utf-8') as f:
            json.dump(result, f, ensure_ascii=False, indent=2)
        print(f"已保存权重到：{output_path}")

